﻿using System;
using System.Runtime.InteropServices;

namespace Yb
{
    public static class CustomPaperHelper
    {
        // ✅ 正确声明：AddForm 接收 HANDLE，不是字符串！
        [DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);

        [DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool ClosePrinter(IntPtr hPrinter);

        // ⚠️ 关键修正：第一个参数是 IntPtr hPrinter，不是 string！
        [DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        private static extern bool AddForm(IntPtr hPrinter, uint level, [In] ref FORM_INFO_1 pFormInfo);

        // EnumForms 也需要句柄
        [DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool EnumForms(IntPtr hPrinter, uint level, IntPtr pForm, uint cbBuf, out uint pcbNeeded, out uint pcReturned);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct FORM_INFO_1
        {
            public uint Flags;
            [MarshalAs(UnmanagedType.LPWStr)]
            public string pName;
            public SIZE Size;
            public RECTL ImageableArea;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SIZE
        {
            public int cx; // micrometers
            public int cy;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct RECTL
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        /// <summary>
        /// 安全添加自定义纸张（正确使用 OpenPrinter + AddForm）
        /// </summary>
        public static YbMessage AddCustomPaper(string printerName, string formName, float widthMm, float heightMm)
        {
            IntPtr hPrinter = IntPtr.Zero;
            try
            {
                if (!OpenPrinter(printerName, out hPrinter, IntPtr.Zero))
                {
                    int err = Marshal.GetLastWin32Error();
                    return new YbMessage(-1, $"OpenPrinter 失败，打印机: {printerName}, 错误码: {err}");
                }

                // 检查是否已存在（可选，此处省略以简化，你可自行加上）
                // 如果要检查，需用 EnumForms(hPrinter, ...)

                var form = new FORM_INFO_1
                {
                    Flags = 0,
                    pName = formName,
                    Size = new SIZE
                    {
                        cx = (int)(widthMm * 1000),
                        cy = (int)(heightMm * 1000)
                    },
                    ImageableArea = new RECTL
                    {
                        left = 0,
                        top = 0,
                        right = (int)(widthMm * 1000),
                        bottom = (int)(heightMm * 1000)
                    }
                };

                if (!AddForm(hPrinter, 1, ref form))
                {
                    int err = Marshal.GetLastWin32Error();
                    return new YbMessage(-2, $"AddForm 失败，错误码: {err}");
                }

                return YbMessage.Success("自定义纸张添加成功");
            }
            catch (Exception ex)
            {
                return new YbMessage(-3, $"AddCustomPaper 异常: {ex.Message}");
            }
            finally
            {
                if (hPrinter != IntPtr.Zero)
                {
                    ClosePrinter(hPrinter);
                }
            }
        }
    }
}